//手写MyPromise
const PENDING = 'pending';//等待
const FULFILLED = 'fulfilled';//成功
const REJECTED = 'rejected';//失败

class MyPromise{
    constructor(executor){//构造函数
        executor(this.resolve, this.reject)
    }
    status = PENDING;//定义成常量，复用
    value = undefined; //成功的值
    reason = undefined; //失败的原因
    successCallback = []; //存储成功回调，用于异步调用,数组支持then链式调用
    failCallback = [];//失败回调
    resolve = value => {//箭头函数，this指向MyPromise
        if(this.status !== PENDING) return;//状态不可逆判断
        //将状态更改为成功
        this.status = FULFILLED;
        this.value = value;
        //判断成功回调是否存在，如果存在就调用
        //this.successCallback && this.successCallback(this.value)
        while(this.successCallback.length){//then链式调用
            this.successCallback.shift()(this.value)
        }
    }
    reject = reason => {
        if(this.status !== PENDING) return;
        //将状态更改为失败
        this.status = REJECTED;
        this.reason = reason;
        //判断失败回调是否存在，如果存在就调用
        //this.failCallback && this.failCallback(this.reason)
        while(this.failCallback.length){
            this.failCallback.shift()(this.reason)
        }
    }
    then (successCallback = value => value, failCallback = reason => {throw reason}) {
        //then 链式调用
        let promise2 = new MyPromise((resolve,reject) => {
            //判断状态
            if(this.status===FULFILLED){
                setTimeout(() =>{//异步代码，为了获取到promise2
                    // let x = successCallback(this.value)
                    // //需要判断x是普通值还是promise对象
                    // //resolve(x);//传递给下一个then
                    // resolvePromise(promise2,x,resolve,reject);
                    try {//增加异常判断
                        let x = successCallback(this.value)
                        resolvePromise(promise2, x, resolve, reject)
                      } catch (e) {
                        reject(e)
                      }
                },0)
            }else if(this.status===REJECTED){
                // let s = failCallback(this.reason)
                // //reject(s)
                // resolvePromise(promise2,s,resolve,reject);
                setTimeout(() =>{//异步代码，为了获取到promise2
                    // console.log(failCallback)
                    // let x = failCallback(this.reason)
                    // //需要判断x是普通值还是promise对象
                    // //resolve(x);//传递给下一个then
                    // resolvePromise(promise2,x,resolve,reject);
                    try {
                        let x = failCallback(this.reason)
                        resolvePromise(promise2, x, resolve, reject)
                      } catch (e) {
                        reject(e)
                      }
                },0)
            }else{//异步情况
                // this.successCallback.push(successCallback);
                // this.failCallback.push(failCallback);
                this.successCallback.push(() => {
                    setTimeout(() => {
                      try {
                        let x = successCallback(this.value)
                        resolvePromise(promise2, x, resolve, reject)
                      } catch (e) {
                        reject(e)
                      }
                    }, 0)
                  })
                  this.failCallback.push(() => {
                    setTimeout(() => {
                      try {
                        let x = failCallback(this.reason)
                        resolvePromise(promise2, x, resolve, reject)
                      } catch (e) {
                        reject(e)
                      }
                    }, 0)
                  })
            }
        })
        return promise2;
    }
    //无论成功失败都会执行
    finally (callback){
        this.then((value)=>{
            return MyPromise.resolve(callback()).then(() => value)
            //callback();
        },(reason)=>{
            // callback();
            // throw reason;
            return MyPromise.resolve(callback()).then(() => {throw reason})
        })
    }
    //处理失败情况
    catch (failCallback){
        return this.then(undefined,failCallback)
    }
    static all (array) {//按照顺序执行所有操作，包括异步操作，参数是数组，返回MyPromise对象，用于then链式调用
        let result = [];
        let index = 0;
        return new MyPromise((resolve,reject) => {
            function addData (key, value) {
                result[key] = value;
                index++;
                if(index === array.length){//判断是否所有异步操作都结束了,都结束了才调用resolve返回
                    resolve(result);
                }
            }
            for(let i = 0; i<array.length; i++){
                let current = array[i];
                if(current instanceof MyPromise){//promise对象
                    current.then(value => addData(i,value), reason => reject(reason))
                }else{//普通值
                    addData(i, array[i]);
                }
            }
        })
    }
    //讲给定的值包装成promise对象，作为返回值
    static resolve (value) {
        if(value instanceof MyPromise) return value;
        return new MyPromise(resolve => resolve(value)); 
    }
}

function resolvePromise (promise2, x, resolve, reject) {
    if(promise2 === x){//判断是否是自己调用自己
        return reject(new TypeError('Chainning cycle detected for promise #<promise>'))
    }
    if(x instanceof MyPromise){//promise对象
        //x.then(value => resolve(value), reason => reject(reason))
        x.then(resolve,reject)
    }else{//普通值
        resolve(x)
    }
}
module.exports = MyPromise;